import { h, shallowRef, computed, provide, inject, defineComponent, useSlots } from 'vue';
import { isFunction } from '@wowon/utils';
import { definePlugin } from '@/components/@comp/create-component';
import { Grid, GridItem } from '@/components/@comp/grid';

const context = { GroupContext: 'GroupContext' };

/** 子组件，分组，用于渲染表单内的分组 */
const Group = defineComponent({
  props: { index: null },
  setup({ index }) {
    const { column, gap, groupIndex, groupList } = inject(context.GroupContext, {});

    const items = computed(() => {
      return groupList.value[index];
    });

    if (
      !items.value ||
      index < 0 ||
      (Array.isArray(groupIndex) && groupIndex.indexOf(index) < 0) ||
      ((typeof groupIndex === 'number' || typeof groupIndex === 'string') && groupIndex !== index)
    ) {
      return () => {};
    }

    return () => {
      const content = h(
        Grid,
        { column, gap },
        {
          default: () =>
            items.value.map((item) =>
              h(GridItem, { colSpan: item.colSpan, rowSpan: item.rowSpan }, { default: item.element }),
            ),
        },
      );
      // const children = slots.default?.();
      // return isVNode(children) ? cloneVNode(children, {})
      return content;

      // return React.isValidElement(children) ? React.cloneElement(children, { children: content }) : content;
    };
  },
});

const FormGroup = definePlugin({
  name: 'FormGroup',
  // priority: 'LAYOUT',
  context,
  subComponent: { Group },
  props: {
    classNames: Object,
    foldConfig: Object,
    actionColumn: Object,
    group: null,
    groupIndex: [Array, Number],
    border: Boolean,
    gap: null,
    column: null,
  },
  main(instance, props) {
    const { classNames = {}, foldConfig, actionColumn, group, groupIndex, border, gap, column } = props;

    const slots = useSlots();

    // const ButtonSubmit = instance.getPlugin('ButtonSubmit');
    const { formColumns } = instance.getPlugin('FormTransformColumns');

    const foldState = shallowRef(!!foldConfig?.defaultFold);

    const withActionColumns = computed(() => {
      const columns = foldState.value
        ? formColumns.data.value.slice(0, foldConfig?.size || column - 1)
        : formColumns.data.value;

      if (actionColumn === null || actionColumn === false) return columns;
      const submitColumn = isFunction(actionColumn)
        ? actionColumn({
            foldEnable: !!foldConfig && formColumns.data.value.length > column - 1,
            columns,
            foldState,
            actionColumnColSpan: column - (columns.length % column),
          })
        : actionColumn;
      return columns.concat({
        // ...ButtonSubmit.actionColumn,
        ...submitColumn,
      });
    });

    // 如果开启了分组模式，使用 slots 内的 Form.Group 渲染表单
    if (group !== void 0) {
      // 将配置列进行分组
      const groupList = computed(() => {
        return withActionColumns.value.reduce((group, item) => {
          if (!item) return group;
          const groupName = item.group || 'default';
          if (Array.isArray(groupName)) {
            groupName.forEach((gname) => {
              if (!group[gname]) group[gname] = [];
              group[gname].push(item);
            });
          } else {
            if (!group[groupName]) group[groupName] = [];
            group[groupName].push(item);
          }
          return group;
        }, {});
      });

      provide(context.GroupContext, {
        column,
        gap,
        groupIndex,
        groupList,
      });

      return { content: () => slots.default?.() };
    }

    return {
      content: () =>
        h(
          Grid,
          { class: classNames.grid, transferStyle: true, border, column, gap },
          {
            default: () => [
              ...withActionColumns.value.map((item) =>
                h(GridItem, { colSpan: item.colSpan, rowSpan: item.rowSpan }, { default: item.element }),
              ),
              slots.default?.(),
            ],
          },
        ),
    };
  },
});

export default FormGroup;
